@file:OptIn(ExperimentalMaterial3Api::class)

package com.fishingwithme.android.ui.screens.spots

import android.util.Log
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.core.content.ContextCompat
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.fishingwithme.android.ui.screens.map.TencentMapWrapper
import com.fishingwithme.android.ui.viewmodels.SpotsHomeModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SpotsScreen(
    navController: NavController,
    viewModel: SpotsHomeModel = hiltViewModel()
) {
    val context = LocalContext.current
    val uiState by viewModel.uiState.collectAsState()
    val coroutineScope = rememberCoroutineScope()
    val mapData = remember { mutableMapOf<String, Any>() }
    var permissionsGranted by remember {
        mutableStateOf(
            ContextCompat.checkSelfPermission(
                context,
                android.Manifest.permission.ACCESS_FINE_LOCATION
            ) == android.content.pm.PackageManager.PERMISSION_GRANTED
        )
    }

    // Add changeKey for monitoring refresh events
    var changeKey by remember { mutableStateOf(uiState.refreshKey ?: "") }

    // Update changeKey when refreshKey changes
    LaunchedEffect(uiState.refreshKey) {
        changeKey = uiState.refreshKey ?: ""
    }

    // Initialize map data when spots are loaded
    LaunchedEffect(uiState.spots, uiState.currentLocation) {
        Log.d("SpotsScreen", "Spots or location changed, spots size: ${uiState.spots.size}")
        // Add spots to map data
        mapData["spots"] = uiState.spots
        Log.d("SpotsScreen", "Updated mapData spots, size: ${uiState.spots.size}")
        // Add current location if available
        uiState.currentLocation?.let { location ->
            mapData["currentLocation"] = location
            Log.d("SpotsScreen", "Updated mapData currentLocation: $location")
        }
    }

    // 权限请求
    DisposableEffect(Unit) {

        val requiredPermissions = arrayOf(
            android.Manifest.permission.INTERNET,
            android.Manifest.permission.ACCESS_FINE_LOCATION,
            android.Manifest.permission.ACCESS_COARSE_LOCATION
        )

        val allGranted = requiredPermissions.all {
            ContextCompat.checkSelfPermission(
                context,
                it
            ) == android.content.pm.PackageManager.PERMISSION_GRANTED
        }

        permissionsGranted = allGranted

        onDispose {
        }
    }

    // Remove Scaffold and use Box directly to fill available space
    Box(modifier = Modifier.fillMaxSize()) {
        TencentMapWrapper(
            modifier = Modifier.fillMaxSize(),
            permissionsGranted = permissionsGranted,
            moduleKey = "spotHome",
            data = mapData,
            changeKey = changeKey, // Pass changeKey to trigger refresh
            onNavigateBack = { dest ->
                navController.navigate(dest)
            },
            onMapCameraChanged = { center ->
                // Update ViewModel with new camera position and zoom level
                viewModel.onMapCameraChanged(center)
                // Load spots based on new map center (distance calculation is handled in ViewModel)
                viewModel.loadSpotsByMapCenter()
            }
        )
    }
}